from flask import Blueprint,jsonify,request
from utils.comm import get_data
from utils.db import db1
from utils.redisconn import r


bp_fiction = Blueprint('fiction',__name__)


@bp_fiction.route('/flogin',methods=['POST'])
def login():
    #获取数据
    # name = request.args.get('name')
    # password = request.args.get('password')
    data = get_data()
    #查询用户信息是否正确
    sql = "select * from euers where name='%s' and password='%s'"%(data['name'],data['password'])
    res = db1.find(sql)

    reslist = []
    if res:
        roleid = res['role_id']
        #根据角色id查询资源列表
        sql11 = "select e.name,e.url from erole_resource as er left join eresources as e on er.resourceid=e.id where roleid=%d"%(int(roleid))
        reslist = db1.find_all(sql11)

        #判断role_id是否为1 管理员  2普通用户
        if int(roleid) ==1:
            r.insert_values('auditidlist',res['id'])


    return jsonify({'code':200,'reslist':reslist,'userid':res['id'],'name':res['name']})


# 小说添加审批
@bp_fiction.route('/newsM',methods=['POST'])
def newsM():
    # 获取参数
    data = get_data()
    #写入小说表
    sql = "insert into enews(title,userid) values ('%s',%d)"%(data['title'],int(data['userid']))

    newsid = db1.update(sql)

    #审批，多个审批员
    idlist = r.get_values('auditidlist')

    #遍历
    min = 0

    #数量最少的
    audit = -1
    if idlist:
        for (i,index) in idlist:
            #i代表审核人id
            key = 'audit%d'%(int(i))
            count = r.list_len(key)
            if index ==0:
                min = count
                auditid = i
            if min > count:
                min = count
                auditid = i

        #加入审核人对应的任务列表
        if int(auditid)>0:
            r.list_push('audit%d'%int(auditid),newsid)
    else:
        return jsonify({'code':10010,'mes':'没有审核员'})

    return jsonify({'code':200})


